var CURRENTUSER, uInfor, south, west, center, exportXls, extType, extForm, themeBtn;

var mainFrame = {
    init: function(){
        Ext.get("logoff").on("click", uLogoff);
        Ext.get("modify").on("click", uInfor.modiPWD, uInfor);
        Ext.get("modiinfo").on("click", uInfor.modiInfo, uInfor);
        Ext.get("userName").dom.innerHTML = CURRENTUSER.username;
        var tabMenu = new Ext.menu.Menu({
            listeners: {
                'show': function(obj){
                    var subMenus = obj.items;
                    subMenus.get('tabMenu_refresh').setDisabled(obj.currentTab != center.getActiveTab());
                    subMenus.get('tabMenu_lock').setDisabled(obj.currentTab.getId() == 'Tab-welcome');
                    subMenus.get('tabMenu_close').setDisabled(!obj.currentTab.closable);
                    subMenus.get('tabMenu_close_others').setDisabled(center.items.getCount() == 1);
                    subMenus.get('tabMenu_lock').setChecked(!obj.currentTab.closable);
                }
            },
            items: [new Ext.menu.CheckItem({
                id: 'tabMenu_lock',
                text: '锁定当前页',
                handler: function(){
                    tabMenu.currentTab.closable = tabMenu.currentTab.closable ? false : true;
                }
            }), {
                id: 'tabMenu_refresh',
                text: '刷新当前页',
                iconCls: 'btn_refresh',
                handler: function(){
                    //center.getEl().mask('加载中......');
                    tabMenu.currentTab.setSrc(tabMenu.currentTab.iframe.dom.src);
                }
            }, {
                id: 'tabMenu_close',
                text: '关闭当前页',
                iconCls: 'btn_close',
                handler: function(obj){
                    center.remove(tabMenu.currentTab);
                }
            }, {
                id: 'tabMenu_close_others',
                text: '关闭其他页',
                iconCls: 'btn_closeall',
                handler: function(){
                    center.items.each(function(item){
                        if (item.closable && item != tabMenu.currentTab) {
                            center.remove(item);
                        }
                    });
                }
            }]
        });
        
        var theme = CQCIS.cookies.get('omstheme') || 'default';
        center = new Ext.TabPanel({
            region: 'center',
            contentEl: 'center',
            activeItem: 0,
            deferredRender: false,
            defaultType: "iframepanel",
            enableTabScroll: true,
            monitorResize: true,
            margins: '0 0 2 2',
            listeners: {
                'contextmenu': function(obj, tab, e){
                    tabMenu.currentTab = tab;
                    tabMenu.showAt(e.getPoint());
                },
                'tabchange': Ext.ux.theme.changeTheme
            },
            items: [{
                anchorSize: '100%',
                closable: false,
                id: 'Tab-welcome',
                defaultSrc: 'welcome.html',
                title: '首页',
                fitToParent: true,
                monitorResize: true,
                loadMask: {
                    msg: '读取中，请稍候......'
                }
            }]
        });
        themeBtn = new Ext.CycleButton({
            showText: true,
            prependText: '当前主题：',
            changeHandler: Ext.ux.theme.apply,
            items: [{
                id: 'default',
                text: '玻璃蓝（默认）',
                checked: (theme == 'default' ? true : false),
                group: 'theme'
            }, {
                id: 'gray',
                text: '金属银',
                checked: (theme == 'gray' ? true : false),
                group: 'theme'
            }, {
                id: 'darkgray',
                text: '夜色灰',
                checked: (theme == 'darkgray' ? true : false),
                group: 'theme'
            }, {
                id: 'purple',
                text: '轻盈紫',
                checked: (theme == 'purple' ? true : false),
                group: 'theme'
            }, {
                id: 'olive',
                text: '春色绿',
                checked: (theme == 'olive' ? true : false),
                group: 'theme'
            }, {
                id: 'slate',
                text: '板岩蓝',
                checked: (theme == 'slate' ? true : false),
                group: 'theme'
            }]
        });
        
        var menuTrees = menuTree.init();
        if (menuTrees.length > 0) {
            var viewport = new Ext.Viewport({
                layout: 'border',
                layoutConfig: {
                    animate: false
                },
                items: [new Ext.BoxComponent({
                    region: 'north',
                    el: 'north',
                    height: 40
                }), {
                    region: 'south',
                    contentEl: 'south',
                    autoScroll: true,
                    // split: true,
                    height: 200,
                    minSize: 100,
                    maxSize: 300,
                    collapsible: true,
                    animCollapse: false,
                    collapsedTitle: '系统提示信息',
                    title: '系统提示信息',
                    cmargins: '0 0 0 0'
                }, {
                    region: 'west',
                    id: 'west-panel',
                    title: '系统菜单',
                    stateful: false,
                    // split: true,
                    width: 180,
                    collapsible: true,
                    // titleCollapse: true,
                    animCollapse: false,
                    layout: 'accordion',
                    items: menuTrees,
                    margins: '0 0 2 0',
                    cmargins: '0 0 2 0',
                    bbar: [themeBtn]
                }, center]
            });
            
            var loading = Ext.get('loading');
            var mask = Ext.get('loading-mask');
            mask.setOpacity(0.8);
            mask.shift({
                xy: loading.getXY(),
                width: loading.getWidth(),
                height: loading.getHeight(),
                remove: true,
                duration: 1,
                opacity: 0.3,
                easing: 'bounceOut',
                callback: function(){
                    loading.fadeOut({
                        duration: 0.2,
                        remove: true
                    });
                }
            });
            
            south = viewport.items.items[1];
            west = viewport.items.items[2];
            south.collapse(false);
            
            if (CURRENTUSER.loginlevel != 0) {
                var chgPwdTime = Ext.Msg.alert('', '密码有效时间至' + CURRENTUSER.lastChgPwdTime.add(Date.DAY, 90).format('Y-m-d'));
                chgPwdTime.hide.defer(5000, chgPwdTime, []);
            }
            
            if (CURRENTUSER.loginNum === 0) {
                uInfor.initPWD();
            }
        } else {
            Ext.Msg.show({
                title: "提示",
                msg: '该用户没有赋予任何权限，无法使用本系统！',
                minHeight: 32,
                minWidth: 200,
                fn: function(par){
                    authDwr.logoff(function(){
                        top.location.replace(CQCIS.ctxPath + "index.html");
                    });
                },
                scope: window,
                cls: 'dlg-top',
                resizable: false,
                closable: false,
                buttons: {
                    'ok': '返回首页'
                }
            });
        }
        /*center.on('resize', function(){
         Ext.each(center.items.items, function(o){
         o.resize = true;
         if (center.getActiveTab().getId() == o.getId()) {
         o.onResize();
         }
         });
         });
         center.on('tabchange', function(p, o){
         if (o.resize) {
         o.onResize();
         }
         });*/
        /*center.on('beforeremove', function(p, o){
         if (!o.closable) {
         CQCIS.alert('该页面已经被锁定，无法关闭！');
         return false;
         }
         });*/
        //printer.SetWebBrowser('top=0,left=0,toolbar=no,Resizable=no,menubar=no,FullScreen=no,Border=no,Closeable=no,width=' + (Ext.getBody().getWidth() + 12) + ',height=' + (Ext.getBody().getHeight() + 82));
    }
};

var menuTree = {
    trees: [],
    reload: function(index){
        var config = menuTree.trees[index].initialConfig;
        menuTree.trees[index].destroy();
        var tree = new CQCIS.tree.DWRTree(config);
        tree.on('click', clickTreeNode, mainFrame);
        tree.on('expand', function(o){
            if (this.root.childNodes.length === 0) {
                this.root.reload();
            }
        }, tree);
        west.insert(index, tree);
        west.doLayout();
        tree.expand(false);
        menuTree.trees = west.items.items;
    },
    init: function(){
        authDwr.getMainMenusOfWorker('0', {
            callback: function(lv){
                if (lv && lv.length > 0) {
                    for (var i = 0; i < lv.length; i++) {
                        var tree = new CQCIS.tree.DWRTree({
                            border: false,
                            autoScroll: true,
                            rootVisible: false,
                            singleExpand: false,
                            title: lv[i].menuName,
                            animate: false,
                            loader: {
                                dwrCall: authDwr.getMainMenusOfWorker,
                                nodeMeta: {
                                    id: 'menuCode',
                                    text: 'menuName',
                                    leaf: 'menuIdend'
                                }
                            },
                            rootText: lv[i].menuName,
                            rootId: lv[i].menuCode
                        });
                        tree.on('click', clickTreeNode, mainFrame);
                        tree.on('expand', function(o){
                            if (o.root.childNodes.length === 0) {
                                o.root.reload();
                            }
                        }, tree);
                        tree.loader.on('beforeload', function(){
                            if (this.collapsed) {
                                return false;
                            } else {
                                return true;
                            }
                        }, tree);
                        menuTree.trees.push(tree);
                    }
                }
            },
            async: false
        });
        return this.trees;
    }
};

function clickTreeNode(node, e){
    if (node.leaf === 0 && node.isExpanded()) {
        node.collapse();
    } else if (node.leaf === 0) {
        node.expand();
    } else if (node.attributes.menuUrl && node.attributes.menuUrl != '#') {
        var tab;
        for (var index = 0; index < center.items.getCount(); index++) {
            if (center.items.items[index].code == node.attributes.menuCode) {
                tab = center.items.items[index];
            }
        }
        if (tab) {
            center.setActiveTab(tab);
        } else if (center.items.getCount() > 8) {
            CQCIS.msg("打开页面不能超过8个,请关闭部分页面重试!");
        } else {
            var cTab, i, j = center.items.getCount();
            for (i = 1; i < j; i++) {
                if (center.items.items[i].closable) {
                    cTab = center.items.items[i];
                    break;
                }
            }
            for (j--; j > i; j--) {
                if (center.items.items[j].closable) {
                    center.remove(center.items.items[j], true);
                }
            }
            
            if (cTab) {
                Ext.DomQuery.selectNode('.x-tab-strip-text', center.getTabEl(cTab)).innerHTML = node.attributes.menuName;
                cTab.setSrc(node.attributes.menuUrl);
                cTab.code = node.attributes.menuCode;
                center.setActiveTab(cTab);
            } else {
                var obj = center.add({
                    monitorResize: true,
                    fitToParent: true,
                    closable: true,
                    code: node.attributes.menuCode,
                    title: node.attributes.menuName,
                    loadMask: {
                        msg: '读取中，请稍候......'
                    }
                });
                center.setActiveTab(obj);
                obj.setSrc(node.attributes.menuUrl);
            }
        }
    }
}

/**
 * 打开标签页方法
 * @param {String} url
 * @param {String} code
 * @param {String} name
 * @param {boolean} forceOpen
 * @param {boolean} forceRefresh
 */
function openWindow(url, code, name, forceOpen, forceRefresh){
    if (!url || url == '#' || !code) {
        return;
    }
    
    var tab;
    for (var i = 0; i < top.center.items.getCount(); i++) {
        if (top.center.items.items[i].code == code) {
            tab = top.center.items.items[i];
        }
    }
    
    if (tab) {
        top.center.setActiveTab(tab);
        if (forceRefresh) {
            tab.setSrc(url);
        }
        return;
    }
	
	var cTab, index, j = top.center.items.getCount();
	for (index = 1; i < j; index++) {
	    if (top.center.items.items[index].closable) {
	        cTab = top.center.items.items[index];
	        break;
	    }
	}
	for (j--; j > index; j--) {
	    if (top.center.items.items[j].closable) {
	        top.center.remove(top.center.items.items[j], true);
	    }
	}
	
	if (cTab) {
	    Ext.DomQuery.selectNode('.x-tab-strip-text', top.center.getTabEl(cTab)).innerHTML = name;
	    cTab.setSrc(url);
	    cTab.code = code;
	    top.center.setActiveTab(cTab);
	} else {
	    var obj = top.center.add({
	        monitorResize: true,
	        fitToParent: true,
	        closable: true,
	        code: code,
	        title: name,
	        loadMask: {
	            msg: '读取中，请稍候......'
	        }
	    });
	    top.center.setActiveTab(obj);
	    obj.setSrc(url);
	    obj.closable = false;
	}
}

Ext.onReady(function(){
    authDwr.getCurrentUser(function(lv){
        if (lv) {
            CURRENTUSER = lv;
            mainFrame.init();
        } else {
            CQCIS.alert('对不起，由于没有登录本系统，您无法正常浏览该页面!', function(){
                if (userName) {
                    logionWin.init();
                } else {
                    top.location.replace('index.html');
                }
            });
        }
    });
});

